package website.lucaswork.survey.mvc.validators;

import org.springframework.beans.factory.annotation.Autowired;
import website.lucaswork.survey.core.converters.StringToLocalDateTimeConverter;
import website.lucaswork.survey.mvc.forms.CreateSurveyForm;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.LocalDateTime;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = SurveyTimeRange.TimeRangeValidator.class)
@Target({ElementType.TYPE})
public @interface SurveyTimeRange {
    String message() default "End time can not be earlier than Start time";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    public class TimeRangeValidator implements ConstraintValidator<SurveyTimeRange, CreateSurveyForm> {

        @Autowired
        StringToLocalDateTimeConverter converter;

        @Override
        public void initialize(SurveyTimeRange constraintAnnotation) {
        }

        @Override
        public boolean isValid(CreateSurveyForm value, ConstraintValidatorContext context) {
            try {
                LocalDateTime fromDate = converter.convert(value.getStartTime());
                LocalDateTime toDate = converter.convert(value.getEndTime());
                return toDate.isAfter(fromDate);
            } catch(Exception e) {
                // this validator is happened before field validation
                // so exception may occur because field validation is not pass
                // just let it go and let field validation do its job
                return true;
            }
        }
    }
}
